package com.gcloud.dropbox;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import java.util.ArrayList;

import java.util.List;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.DropboxAPI.DropboxFileInfo;
import com.dropbox.client2.DropboxAPI.Entry;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.android.AuthActivity;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.exception.DropboxIOException;
import com.dropbox.client2.exception.DropboxParseException;
import com.dropbox.client2.exception.DropboxPartialFileException;
import com.dropbox.client2.exception.DropboxServerException;
import com.dropbox.client2.exception.DropboxUnlinkedException;
import com.dropbox.client2.session.AccessTokenPair;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.Session.AccessType;
import com.dropbox.client2.session.TokenPair;
import com.example.gcode.Archivos;
import com.example.gcode.GCloudSingleton;
import com.example.gcode.R;
import com.gcloud.dropbox.ListDropBoxFile;
import com.gcloud.dropbox.UploadDropboxFile;
import com.gcloud.persistance.SQLiteHandler;
import com.gfilechooser.utils.FileUtils;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.services.drive.Drive;
import com.utils.Constants;
import com.utils.GCloudUtil;
import com.utils.Message;

import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class DownloadDropBoxFileActivity extends Activity {
	private static String TAG = DownloadDropBoxFileActivity.class.getSimpleName();
	private ProgressDialog pDialog;	
	Drive service;
	GoogleAccountCredential credential;
	private static final int REQUEST_ACCOUNT = 1;
	private static final int REQUEST_CODE = 100;

	/* DROP BOX THINGS */
	final static private String APP_KEY = "bx9eufdsdzpbxs5";
	final static private String APP_SECRET = "tz6vorkhj2xvfv1";
	public static boolean mLoggedIn = false;
	final static private String ACCOUNT_PREFS_NAME = "prefs";
	final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
	final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
	DropboxAPI<AndroidAuthSession> mApi;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.archivos_list);

		Bundle bund=getIntent().getExtras();
		String filePath="";
		String fileName="";
		String account="";
		if(bund!=null){
			filePath=bund.getString(Constants.FILE_URL);
			fileName=bund.getString(Constants.FILE_NAME);
			account=bund.getString(Constants.FILE_ACCOUNT);
		}
		
		dropBoxAuthentication(filePath, fileName, account);
		// showFilesOnUi();
		// listFiles();

	}

	private void showChooser() {
		// Use the GET_CONTENT intent from the utility class
		Intent target = FileUtils.createGetContentIntent();
		// Create the chooser Intent
		Intent intent = Intent.createChooser(target,
				getString(R.string.chooser_title));
		try {
			startActivityForResult(intent, REQUEST_CODE);
		} catch (ActivityNotFoundException e) {
			// The reason for the existence of aFileChooser
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.i("jalskjdf", "guaro!!");
		switch (item.getItemId()) {
		case R.id.menu_upload:

			Log.i("here", "upload");
			showChooser();
			break;
		case R.id.menu_download:
			Log.i("here", "download");
			break;
		case R.id.menu_delete:
			Log.i("here", "delete");
			break;
		case R.id.menu_bookmark:
			Log.i("here", "bookmark");
			break;
		case R.id.menu_save:
			Log.i("here", "save");
			break;
		case R.id.menu_search:
			Log.i("here", "search");
			break;
		case R.id.menu_google_drive:
			Log.i("here", "google drive");
			break;
		case R.id.menu_dropbox:
			Log.i("here", "dropbox");
			break;
		}
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.layout.menu_layout, menu);
		return true;
	}

	private void dropBoxAuthentication(String filePath, String fileName, String account) {
		AndroidAuthSession session = buildSession(account);
		mApi = new DropboxAPI<AndroidAuthSession>(
				session);
		checkAppKeySetup();
		if (DownloadDropBoxFileActivity.mLoggedIn) {
			Log.i("v()", "is still logged");
			new CargarArchivos().execute(filePath, fileName);
		} else {
			Log.i("DropBoxAuthentication()", "is not logged");
			mApi.getSession().startAuthentication(DownloadDropBoxFileActivity.this);
		}
		setLoggedIn(mApi.getSession().isLinked());
		Log.i("DropBoxAuthentication", "Logged: "
				+ mApi.getSession().isLinked());
		showToast("Logged: " + mApi.getSession().isLinked());
	}

	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_ACCOUNT:
			if (resultCode == RESULT_OK && data != null
					&& data.getExtras() != null) {
				String accountName = data
						.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
				// credential.setSelectedAccountName(accountName);
				// service = getDriveServices(credential);
				// new CargarArchivos().execute();
				Log.i("GCLOUD", "Ya entre a doInBackground :)");
				// ListGoogleFile listGoogle = new ListGoogleFile(service,
				// getApplicationContext());
				Log.i("OnActivitty", "before to execute");
				// try {
				// listGoogle.execute();
				// showFilesOnUi();
				// } catch (Exception e) {
				// Log.i("Exception catch", e.toString());
				// //
				// startActivityForResult(credential.newChooseAccountIntent(),
				// // REQUEST_CONFIRMATION);
				// }
				Log.i("OnActivitty", "after execute");

			}
			break;
		case REQUEST_CODE:
			if (resultCode == RESULT_OK) {
				if (data != null) {
					// Get the URI of the selected file
					final Uri uri = data.getData();
					try {
						// Create a file instance from the URI
						final File file = FileUtils.getFile(uri);
						showToast("File selected: " + file.getAbsolutePath());
						UploadDropboxFile uploadDropBoxFile = new UploadDropboxFile(
								DownloadDropBoxFileActivity.this, mApi, "/", file);
						uploadDropBoxFile.execute();
						// UploadGoogleFile googleFile = new UploadGoogleFile(
						// service, Archivos.this, file);
						// googleFile.execute();
					} catch (Exception e) {
						Log.e("FileSelectorTestActivity", "File select error",
								e);
					}
				}
			}
			break;
		// case REQUEST_CONFIRMATION:
		// startActivityForResult(credential.newChooseAccountIntent(),
		// REQUEST_ACCOUNT);
		// break;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
//		if (mApi.getSession() == null) {
//			Log.i("onResume()", "session null");
//			return;
//		}
//		AndroidAuthSession session = mApi.getSession();
//
//		if (session.authenticationSuccessful()) {
//			try {
//				session.finishAuthentication();
//				TokenPair tokens = session.getAccessTokenPair();
//				storeKeys(tokens.key, tokens.secret);
//				setLoggedIn(true);
//			} catch (IllegalStateException e) {
//				showToast("Couldn't authenticate with Dropbox:"
//						+ e.getLocalizedMessage());
//				Log.i(TAG, "Error authenticating", e);
//			}
//		}
	}

	public void showToast(final String toast) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), toast,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	public void checkAppKeySetup() {
		if (APP_KEY.startsWith("CHANGE") || APP_SECRET.startsWith("CHANGE")) {
			showToast("You must apply for an app key and secret from developers.dropbox.com, and add them to the GCloud ap before trying it.");
			return;
		}
		Intent testIntent = new Intent(Intent.ACTION_VIEW);
		String scheme = "db-" + APP_KEY;
		String uri = scheme + "://" + AuthActivity.AUTH_VERSION + "/test";
		testIntent.setData(Uri.parse(uri));
		PackageManager pm = getPackageManager();
		if (0 == pm.queryIntentActivities(testIntent, 0).size()) {
			showToast("URL scheme in your app's "
					+ "manifest is not set up correctly. You should have a "
					+ "com.dropbox.client2.android.AuthActivity with the "
					+ "scheme: " + scheme);
		}
	}

	public AndroidAuthSession buildSession(String account) {
		AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
		AndroidAuthSession session;

		String[] stored = getKeys(account);
		if (stored != null) {
			Log.i("buildSession", " getting key stored:");
			AccessTokenPair accessToken = new AccessTokenPair(stored[0],
					stored[1]);
			session = new AndroidAuthSession(appKeyPair, AccessType.DROPBOX,
					accessToken);
			setLoggedIn(true);
		} else {
			Log.i("buildSession",
					"getting key not stored, going to build a new one");
			session = new AndroidAuthSession(appKeyPair, AccessType.DROPBOX);
		}
		if (session != null) {
			Log.i("buildSession", " session is not null");
		}
		return session;
	}

	public String[] getKeys(String account) {
		SQLiteHandler sqliteHandler = new SQLiteHandler(DownloadDropBoxFileActivity.this,
				Constants.GCLOUD, null, Constants.DB_VERSION);
		String []keys=sqliteHandler.getKeyAccount(account);
		//if(keys.length>0&&keys.length<3){
			return keys;
		//}
		//return null;
		//SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
//		String key = keys[0];//prefs.getString(ACCESS_KEY_NAME, null);
//		String secret = keys[1];//prefs.getString(ACCESS_SECRET_NAME, null);
//		if (key != null && secret != null) {
//			String[] ret = new String[2];
//			ret[0] = key;
//			ret[1] = secret;
//			return ret;
//		} else {
//			return null;
//		}
	}

	public void setLoggedIn(boolean loggedIn) {
		DownloadDropBoxFileActivity.mLoggedIn = loggedIn;
		Log.i("setLoggedIn() ", String.valueOf(mLoggedIn));
	}

	public void storeKeys(String key, String secret) {
		// Save the access key for later
		SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
		Editor edit = prefs.edit();
		edit.putString(ACCESS_KEY_NAME, key);
		edit.putString(ACCESS_SECRET_NAME, secret);
		edit.commit();
	}

	class CargarArchivos extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(DownloadDropBoxFileActivity.this);
			pDialog.setMessage(Message.CHARGING_FILES);
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		GCloudSingleton gCloudSingleton;
		private String mErrorMsg;
		private String mPath = "/";
		List<Entry> entriesFromDrive = new ArrayList<Entry>();

		/**
		 * getting Inbox JSON
		 * */
		protected String doInBackground(String... args) {

			String downloadPath=args[0];
			
			String fileToDownload=args[1];			
			Log.i("GCLOUD", "Ya entre a doInBackground, file to download: "+fileToDownload+"  "+args[0]);
			File fileW=android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
			
			File file = new File(fileW+"/"+fileToDownload);
	    	FileOutputStream outputStream=null;
	    	String mimeType="";
	    	try {
				outputStream = new FileOutputStream(file);
				DropboxFileInfo info;
				try {
					info = mApi.getFile(downloadPath,
							null, 
							outputStream, 
							null);
					Log.i("DbExampleLog", "The file's rev is: " + info.getMetadata().rev);
					mimeType=info.getMetadata().mimeType;
				} catch (DropboxException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
					return "false";
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				return "false";
			}
	    	openFile(fileToDownload, mimeType);
			return "true";

		}
		
		String globalMPath="";

		
		private void openFile(String name, String mimeType){
			try{
				java.io.File file=android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
				java.io.File path=new java.io.File(file,name);
				Uri uri=Uri.fromFile(path);
				    Intent intent=new Intent(Intent.ACTION_VIEW);
				    intent.setDataAndType(uri, mimeType);
				 startActivity(intent);
				}catch(Exception e){
					Log.i("Clicke init: ","Error: "+e);
				}
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			if (file_url.equalsIgnoreCase("true")) {
				showToast(Message.FILE_DOWNLOADED);
//				Intent newIntent = new Intent(DownloadDropBoxFileActivity.this,
//						Archivos.class);
//				startActivity(newIntent);
			} else {
				showToast(Message.ERROR_DOWNLOADING_FILE);
			}
			// if(){
			// startActivityForResult(credential.newChooseAccountIntent(),
			// REQUEST_ACCOUNT);
			// }
			// updating UI from Background Thread			
		}

	}

}
